﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SPA_Prototype.Model
{
    class CurrencyManagement
    {
        private int _ExchangeRate;
        private DatabaseDataSet _Dataset;
        private DatabaseDataSet.CurrencyTableDataTable _DataTable;
        private DatabaseDataSetTableAdapters.CurrencyTableTableAdapter _Adt;

        // constructor
        public CurrencyManagement(DatabaseDataSet dt)
        {
            _Dataset = dt;
            _DataTable = _Dataset.CurrencyTable;

            _Adt = new DatabaseDataSetTableAdapters.CurrencyTableTableAdapter();

            LoadDB();
        }

        // Property       
        public int ExchangeRate
        {
            get { return _ExchangeRate; }
            set
            {
                if (value == 0) return;
                _ExchangeRate = value;
                if (_DataTable.Rows.Count == 0) _DataTable.AddCurrencyTableRow(21000);
                _DataTable[0].ExchangeRate = _ExchangeRate;
                UpdateDB();
            }
        }

        // Method : LoadDB, UpdateDB, ConvertToVND, ConvertToUSD
        private void LoadDB()
        {
            _Adt.Fill(_DataTable);
            if (_DataTable.Rows.Count != 0) _ExchangeRate = _DataTable[0].ExchangeRate;
            else _ExchangeRate = 21000;
        }

        private void UpdateDB()
        {
            try
            {
                _Adt.Update(_DataTable);
                MessageBox.Show("Successful !", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public int ConvertToVND(double USD)
        {
            return (int) USD * _ExchangeRate;
        }

        public double ConvertToUSD(int VND)
        {
            return (double)VND / _ExchangeRate;
        }
    }
}
